import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import moment from "moment";
import uniq from 'lodash/uniq';
import cloneDeep from 'lodash/cloneDeep';
import { Modal, Row, Col, Form, Card, Input, Select, Icon, Button, message, DatePicker, Popconfirm} from "antd";
import MaintainPerson from '../../Form/MaintainPerson';
import PtathCuring from '../../Path/Components/PtathCuring';
import PathAdd from "../../Path/Components/PathAdd";
import PathChoose from "../../Path/Components/PathChoose";
import CuingList from "../../Path/Components/CuingList";
import PlanTime from "../../Form/PlanTime";
import styles from '../../Pbulic.less';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

@connect(({ plan, path, global }) => ({
  loading:plan.loading,
  detaildata:plan.detaildata,
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  pathcuring:path.pathcuring,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class PlanAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.detailId = this.props.match.params.id && this.props.match.params.id!='detail' ? this.props.match.params.id : 0;
    this.state={
      maintenanceSateId:null,
      removeIds:[],
      devChoose:[],
      pathChoose:[],
      modalPathChooseVisible: false,
      modalCuringChooseVisible: false,
      modalPathAddVisible: false,
      planTypeState:"01",
      planTimeTemp:[],
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;

    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });
    // dispatch({
    //   type: 'global/fetch_select_maintenman',
    // });


    if (this.detailId!==0) {
        // 编辑时 读取详情
        dispatch({
          type: "plan/fetch_plan_info",
          payload: {
            planId: this.detailId
          }
        })
          .then(() => {
            //根据维保id，获取相关人员
            const deptId = this.props.detaildata.maintenanceId;
            this.props.dispatch({
              type: 'global/fetch_select_maintenman',
              payload: {
                deptId,
                userType:"02",
              }
            })
          })
          .then(()=>{
            this.setState({
              maintenanceSateId:this.props.detaildata.maintenanceId,
              planTypeState:this.props.detaildata.planType,
            })
        });
    }
  }


  // 维保单位关联人搜索事件-------------------------------------
  handleSearchMaintain = ( value, oldvalue ) =>{
    const { dispatch } = this.props;
    const maintenanceId=value.maintenanceId;
    const userId=value.userId;
    const loadData=value.loadData;

    if(value.maintenanceId != oldvalue.maintenanceId){
      dispatch({
        type: "path/fetch_curing_clear",
      })
    }

    if(userId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_maintenman',
      })
    }

    if(loadData && maintenanceId!==0){
      this.handleChageMaintenance(maintenanceId);
      dispatch({
        type: 'global/fetch_select_maintenman',
        payload: {
          deptId:maintenanceId,
        },
      })
    }
  }
  checkMaintain =  (rule, value, callback) => {
    if (value.userId!==0) {
      callback();
      return;
    }
    callback('请选择维保单位及相关人员');
  }




  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch, pathcuring } = this.props;
        const planId = this.detailId!=0 ? this.detailId : undefined
        const action = this.detailId!=0 ? 'edit' : 'add';
        // console.log(values)
        const devIds = pathcuring && pathcuring.length > 0 ? uniq(pathcuring.map(item=>item.devId)) : undefined
        if(!devIds){
          message.error("请先选择路线和养护点");
          return false;
        }

        if(values.firstExecuteTime){
          values.startExecuteTime = values.firstExecuteTime[0].format("YYYY-MM-DD");
          values.stopExecuteTime = values.firstExecuteTime[1].format("YYYY-MM-DD");
        }


        if(values.planTime){
          values.beginTime = values.planTime[0].unix() * 1000;
          values.endTime = values.planTime[1].unix() * 1000;
        }

        if(values.maintenanceInfo && values.maintenanceInfo.maintenanceId!==0 && values.maintenanceInfo.userId!=0){
          values.maintenanceId = values.maintenanceInfo.maintenanceId;
          values.maintainManId = values.maintenanceInfo.userId;
        }



        // 执行时间 格式化
        // if(values.planType=="01" && values.startExecuteTime.value1){
        //   values.startExecuteTime = values.startExecuteTime.value1;
        // }else if((values.planType=="02" || values.planType=="03") && values.startExecuteTime.value1 && values.startExecuteTime.value2){
        //   values.startExecuteTime = values.startExecuteTime.value1+","+values.startExecuteTime.value2;
        // }else{
        //   values.startExecuteTime = undefined;
        // }
        // if(values.startExecuteTime){
        //   values.startExecuteTime = values.startExecuteTime.unix() * 1000;
        // }

        // if(values.planType=="01" && values.stopExecuteTime.value1){
        //   values.stopExecuteTime = values.stopExecuteTime.value1;
        // }else if((values.planType=="02" || values.planType=="03") && values.stopExecuteTime.value1 && values.stopExecuteTime.value2){
        //   values.stopExecuteTime = values.stopExecuteTime.value1+","+values.stopExecuteTime.value2;
        // }else{
        //   values.stopExecuteTime = undefined;
        // }
        //
        // if(!values.startExecuteTime || !values.stopExecuteTime){
        //   values.startExecuteTime = undefined; // 其中一个无值就赋空
        //   values.stopExecuteTime = undefined;
        // }



        devIds && dispatch({
          type: `plan/${action}_plan`,
          payload: {
            ...values,
            devIds,
            planId,
            // devIds:pathcuring.map(e=>e.devId).join(","),
            maintenanceInfo:undefined,
            planTime:undefined,
            firstExecuteTime:undefined,

          }
        })
          .then(() => {
            this.handleReset();
            message.success(this.detailId === 0 ? "计划已添加成功" : "计划已修改成功");
            this.goBack();
          });
      }
    });
  }

  goBack = () => {
    const { dispatch, location } = this.props;
    if(this.detailId===0){
      router.push({ pathname:`/maintain/plan/list`});
    }else{
      router.push({ pathname:`/maintain/plan/list`,  query: { ...location.query} });
    }
  }

  handleReset = () => {
    const { match } = this.props;
    this.setState({
      maintenanceSateId:match.params.id ? this.state.maintenanceSateId : null,
      removeIds:[],
      devChoose:[],
      pathChoose:[],
      modalPathChooseVisible: false,
      modalCuringChooseVisible: false,
      modalPathAddVisible: false,
    })
    this.props.form.resetFields();
  };

  // 维保单位切换时，更新state
  handleChageMaintenance = (value) => {
    this.setState({
      maintenanceSateId:value,
    })
  }

  // 显示选择唯一维保单位路线弹窗
  handlePathChooseModalVisible= flag => {
    const { dispatch } = this.props;
    dispatch({
      type: `path/fetch_data_clear`,
    }).then(()=>{
      this.setState({
        modalPathChooseVisible: !!flag,
      });
    })
  };

  // 显示选养护点弹窗
  handleCuringChooseModalVisible= flag => {
    const { dispatch } = this.props;
    dispatch({
      type: `path/fetch_data_clear`,
    }).then(()=>{
      this.setState({
        modalCuringChooseVisible: !!flag,
      });
    })

  };


  // 添加养护路线
  handleSubmitPathChoose = (e) => {
    e.preventDefault();
    const { dispatch } = this.props;
    const { pathChoose } = this.state;
    if (pathChoose && pathChoose.length>0) {
      dispatch({
        type: `path/fetch_path_equipment_merge`,
        payload: {
          lineIds: pathChoose
        }
      }).then(()=>{
        this.handlePathChooseModalVisible();
      })
    }
  }

  // 表格选中路线值，通过路线获取养护点
  handleSelectPathIds = (pathChoose) =>{
    this.setState({
      pathChoose:pathChoose,
    })
  }

  // 添加养护点
  handleSubmitCruingChoose = items =>{
    const { dispatch } = this.props;
    const { devChoose } = this.state;
    if (devChoose && devChoose.length>0) {
      dispatch({
        type: `path/fetch_curingupdate_add`,
        payload: devChoose
      }).then(()=>{
        this.handleCuringChooseModalVisible();
      })
    }
  }

  // 表格选中设备值，放到本页
  handleSelectCruing = items =>{
    this.setState({
      devChoose:items,
    })
  }


  // 删除选中的节点
  handleSelectRemove = items =>{
    this.setState({
      removeIds:items,
    })
  }

  handleRemoveCuring = () =>{
    const { dispatch } = this.props;
    const { removeIds } = this.state;
    if (removeIds && removeIds.length>0) {
      dispatch({
        type: `path/fetch_curingupdate_del`,
        payload: removeIds
      })
    }
  }


  // 显示新增修改model
  handlePathModalVisible= flag => {
    this.setState({
      modalPathAddVisible: !!flag,
    });
  };

  // 设备新增、编辑后model回调
  handlePathModelCallBack=()=>{
    this.handlePathModalVisible(false);
  }


  // 计划类型变更操作
  handleSelectPlanType = (value) =>{
    this.setState({
      planTypeState:value,
    },()=>{
      const { form } = this.props;
      form.setFieldsValue({
        startExecuteTime:undefined,
        // startExecuteTime:{value1:null,value2:null},
        // stopExecuteTime:{value1:null,value2:null},
      })
    })

  }

  // 计划时间发送变化时
  handlePlanTimeChange = (dates,dateStrings) =>{
    const { form } = this.props;
    form.setFieldsValue({
      firstExecuteTime:undefined,
    })

    this.setState({
      planTimeTemp:dates,
    })

  }

  // 不可选日期
  handleDisabledDate = (current) => {
    const { planTimeTemp } =this.state;
    if(planTimeTemp && planTimeTemp.length>0){
      const disabledTimeTemp=cloneDeep(planTimeTemp);
        disabledTimeTemp[1]=disabledTimeTemp[1].add(1,'days')
      return current < disabledTimeTemp[0] || current > disabledTimeTemp[1];
    }else{
      return false
    }
  }

  handleDisabledDatePlanTime= (current) => {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  }


  render() {
    const { match, detaildata, dictionaries, selectSource, pathcuring,loading } = this.props;
    const { maintenanceSateId, modalPathChooseVisible, modalCuringChooseVisible, modalPathAddVisible, removeIds, planTypeState, planTimeTemp } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    };



    return (
     <Fragment>
      <Row gutter={{ md: 8, lg: 24, xl: 48 }} >
        <Col md={8} sm={24} className={styles.small_card} style={{paddingRight:6}}>
          <Card title={"计划信息"}
                extra={
                  <div >
                    <Button  type="primary"
                             disabled={pathcuring.length>0 ? false : true}
                             onClick={(e)=>this.handleFormSubmit(e)}
                             loading={loading.model_submit}
                    >
                      { this.detailId ? '编辑' : '提交'}
                    </Button>
                  </div>
                }
          >
            <Form layout="horizontal">
              <Row gutter={24}>

                <Col span={24}>
                  {
                    this.detailId!==0 &&
                    <FormItem {...formItemLayout} label="计划编号" colon={false}>
                      {getFieldDecorator("planCode", {
                        initialValue: this.detailId === 0 ? undefined : detaildata.planCode,
                        rules: [
                          // { required: true, message: "请输入设备名称" },
                        ]
                      })(
                        <Input placeholder="请输入计划编号" disabled={true}/>
                      )}
                    </FormItem>
                  }
                </Col>



                <Col span={24}>
                  <FormItem {...formItemLayout} label="计划名称" colon={false}>
                    {getFieldDecorator("planName", {
                      initialValue: this.detailId === 0 ? undefined : detaildata.planName,
                      rules: [
                        { required: true, message: "请输入计划名称" },
                      ]
                    })(
                      <Input placeholder="请输入计划名称" />
                    )}
                  </FormItem>
                </Col>
                <Col span={24}>
                  <FormItem {...formItemLayout} label="计划类型" colon={false}>
                    {getFieldDecorator("planType", {
                      initialValue: this.detailId === 0 ? planTypeState : (detaildata.planType && detaildata.planType),
                      rules: [
                        { required: true, message: "请选择计划类型" },
                      ]
                    })(
                      <Select  style={{ width: '100%' }}
                               onSelect={this.handleSelectPlanType}
                      >
                        {dictionaries.planExecuteTime && dictionaries.planExecuteTime.map(item => (
                          <Option key={item.value} value={item.value}>{item.label}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>

                <Col span={24}>
                  <FormItem {...formItemLayout} label="执行周期" colon={false}>
                    {getFieldDecorator("executeTime", {
                      initialValue: this.detailId === 0 ? undefined : detaildata.executeTime,
                      rules: [
                        { required: true, message: "请输入执行周期" },
                      ]
                    })(
                      <Input placeholder="请输入执行周期" addonBefore="每" addonAfter={planTypeState=="01" ? "日" : planTypeState=="02" ? "周" : planTypeState=="03" ? "月" : '--'}/>
                    )}
                  </FormItem>
                </Col>
                {/*
                 <Col span={24}>
                    <FormItem {...formItemLayout} label="执行时间" colon={false} style={{marginBottom:10}}>
                      {getFieldDecorator("startExecuteTime", {
                        initialValue: this.detailId === 0 ? {value1:null,value2:null} : planTypeState=="01" && detaildata.startExecuteTime ? {value1:detaildata.startExecuteTime} : detaildata.startExecuteTime && {value1:detaildata.startExecuteTime.split(",")[0],value2:detaildata.startExecuteTime.split(",")[1]},
                        rules: [
                          // { required: true, message: "请输入设备名称" },
                        ]
                      })(
                        <PlanTime planType={planTypeState} addonAfter={"到"} />
                      )}
                    </FormItem>
                `</Col>
                */}

                <Col span={24}>
                  <FormItem {...formItemLayout} label="计划时间" colon={false}>
                    {getFieldDecorator("planTime", {
                      initialValue: this.detailId === 0 ? undefined : (detaildata.beginTime && detaildata.endTime ?  [moment(Number(detaildata.beginTime)),moment(Number(detaildata.endTime))]  : undefined),
                      rules: [
                        { required: true, message: "请选择计划时间" },
                      ]
                    })(
                      <RangePicker
                        format="YYYY-MM-DD"
                        placeholder={['开始时间', '结束时间']}
                        style={{ width: "100%" }}
                        onChange={this.handlePlanTimeChange}
                        disabledDate={this.handleDisabledDatePlanTime}
                      />
                    )}
                  </FormItem>
                </Col>


                {
                  planTimeTemp.length>0 &&
                  <Col span={24}>
                    <FormItem {...formItemLayout} label="首次执行时间" colon={false}>
                      {getFieldDecorator("firstExecuteTime", {
                        initialValue: this.detailId === 0 ? undefined : (detaildata.startExecuteTime && detaildata.startExecuteTime ?  [moment(Number(detaildata.startExecuteTime)),moment(Number(detaildata.stopExecuteTime))]  : undefined),
                        rules: [
                          { required: true, message: "请选择首次执行时间" },
                        ]
                      })(
                        <RangePicker
                          format="YYYY-MM-DD"
                          placeholder={['开始时间', '结束时间']}
                          disabledDate={this.handleDisabledDate}
                          style={{ width: "100%" }}
                        />
                      )}
                    </FormItem>
                  </Col>
                }



                {/*
                <Col span={24}>
                  <FormItem {...formItemLayout} label="结束时间" colon={false}>
                    {getFieldDecorator("endTime", {
                      initialValue: this.detailId === 0 ? undefined : (detaildata.endTime && moment(Number(detaildata.endTime))),
                    })(
                      <DatePicker
                        placeholder="请输入结束时间"
                        style={{ width: "100%" }}
                      />
                    )}
                  </FormItem>
                </Col>
                */}


                <Col span={24}>
                  <FormItem {...formItemLayout} label="维保单位" colon={false}>
                    {getFieldDecorator("maintenanceInfo", {
                      initialValue: this.detailId === 0 ? {maintenanceId:0,userId:0} : {maintenanceId:detaildata.maintenanceId,userId:detaildata.maintainManId},
                      rules: [{required: true, message: "请选择维保单位及相关人员"},{validator: this.checkMaintain}],
                    })(
                      <MaintainPerson
                        span={24}
                        Mplaceholder={"请选择路线或养护点"}
                        placeholder={"请选择养护人"}
                        maintainData={selectSource.maintenance}
                        personnelData={selectSource.maintenman}
                        onChange={this.handleSearchMaintain}
                      />
                    )}
                  </FormItem>
                </Col>


                <Col span={24}>
                  <FormItem {...formItemLayout} label="备注" colon={false}>
                    {getFieldDecorator("remarks", {
                      initialValue: this.detailId === 0 ? undefined : detaildata.remarks,
                      rules: [{ max: 500, message: "不超过500个字" }]
                    })(
                      <TextArea
                        placeholder="请输入备注内容"
                        autosize={{ minRows: 3, maxRows: 6 }}
                      />
                    )}
                  </FormItem>
                </Col>

              </Row>
            </Form>

          </Card>
        </Col>
        <Col md={16} sm={24}  className={styles.small_card} style={{paddingLeft:6}}>
          <Card
            title={"计划路线设置"}
            bodyStyle={{padding:1}}
            extra={
              <div >
                <Button  type="primary"
                         style={{marginRight:15}}
                         disabled={maintenanceSateId ? false : true}
                         onClick={this.handlePathChooseModalVisible}
                >
                  添加养护路线
                </Button>
                <Button  type="primary"
                         style={{marginRight:15}}
                         disabled={maintenanceSateId ? false : true}
                         onClick={this.handleCuringChooseModalVisible}
                >
                  添加养护点
                </Button>
                <Button  type="primary"
                         style={{marginRight:15}}
                         disabled={pathcuring.length>0 ? false : true}
                         onClick={this.handlePathModalVisible}
                >
                  保存为新路线
                </Button>
                <Popconfirm title={<span>是否确定要删除?<br/>删除后需点击编辑后生效</span>}  onClick={this.handleRemoveCuring} okText="是" cancelText="否">
                <Button  type="danger"
                         disabled={removeIds.length>0 ? false : true}

                >
                  删除
                </Button>
                </Popconfirm>
              </div>
            }
          >
            {
              (this.detailId === 0 ? maintenanceSateId : detaildata.maintenanceId) &&
              <PtathCuring
                // detailInfoId={detailInfoId}
                // doDel={doDel}
                selectCallBack={this.handleSelectRemove}
                refreshStop={this.handleUpdateDelOver}
                tableData={pathcuring}
                // loading={loadingdev}
              />
            }
            {
              !(this.detailId === 0 ? maintenanceSateId : detaildata.maintenanceId) &&
              <div style={{textAlign:'center',padding:30,color:'rgba(0, 0, 0, 0.45)'}}>请先选择维保单位</div>
            }

          </Card>
        </Col>



      </Row>


       <Modal
         title={"添加养护路线"}
         visible={modalPathChooseVisible}
         onOk={this.handleSubmitPathChoose}
         onCancel={() => this.handlePathChooseModalVisible(false)}
         width={900}
         destroyOnClose={true}
         bodyStyle={{padding:0}}

       >
         <PathChoose
           maintenanceId={maintenanceSateId}
           selectCallBack={this.handleSelectPathIds}
         />
       </Modal>

       <Modal
         title={"添加养护点"}
         visible={modalCuringChooseVisible}
         onOk={this.handleSubmitCruingChoose}
         onCancel={() => this.handleCuringChooseModalVisible(false)}
         width={900}
         destroyOnClose={true}
         bodyStyle={{padding:0}}
       >
         <CuingList
           maintenanceId={maintenanceSateId}
           // doAdd={doAdd}
           selectCallBack={this.handleSelectCruing}
           // refreshStop={this.handleUpdateAddOver}
         />
       </Modal>

       <PathAdd
         visible={modalPathAddVisible}
         onCancel={e => this.handlePathModalVisible(e)}
         callback={this.handlePathModelCallBack}
         maintenanceId={maintenanceSateId}
         detailId={0}
         devIds={pathcuring && pathcuring.length>0 && pathcuring.map(item=>item.devId)}
         // // dictionaries={dictionaries}
         // selectSource={selectSource}
       />
     </Fragment>
    );
  }
}
